{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 人工势场法轨迹规划\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import copy\n",
    "from celluloid import Camera  # 保存动图时用，pip install celluloid\n",
    "%matplotlib qt5"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 初始参数设置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "## 初始化车的参数\n",
    "d = 3.5  #道路标准宽度\n",
    "\n",
    "W = 1.8  #  汽车宽度\n",
    "\n",
    "L = 4.7  # 车长\n",
    "\n",
    "P0 = np.array([0, - d / 2, 1, 1]) #车辆起点位置，分别代表x,y,vx,vy\n",
    "\n",
    "Pg = np.array([99, d / 2, 0, 0]) # 目标位置\n",
    "\n",
    "# 障碍物位置\n",
    "Pobs = np.array([\n",
    "    [15, 7 / 4, 0, 0],    \n",
    "    [30, - 3 / 2, 0, 0],\n",
    "    [45, 3 / 2, 0, 0], \n",
    "    [60, - 3 / 4, 0, 0], \n",
    "    [80, 3/2, 0, 0]])\n",
    "\n",
    "P = np.vstack((Pg,Pobs))  # 将目标位置和障碍物位置合放在一起\n",
    "\n",
    "Eta_att = 5  # 引力的增益系数\n",
    "\n",
    "Eta_rep_ob = 15  # 斥力的增益系数\n",
    "\n",
    "Eta_rep_edge = 50   # 道路边界斥力的增益系数\n",
    "\n",
    "d0 = 20  # 障碍影响的最大距离\n",
    "\n",
    "num = P.shape[0] #障碍与目标总计个数\n",
    "\n",
    "len_step = 0.5 # 步长\n",
    "\n",
    "n=1\n",
    "\n",
    "Num_iter = 300  # 最大循环迭代次数\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 数据存储变量定义\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "path = []  # 保存车走过的每个点的坐标\n",
    "delta = np.zeros((num,2)) # 保存车辆当前位置与障碍物的方向向量，方向指向车辆；以及保存车辆当前位置与目标点的方向向量，方向指向目标点\n",
    "dists = [] # 保存车辆当前位置与障碍物的距离以及车辆当前位置与目标点的距离\n",
    "unite_vec = np.zeros((num,2)) #  保存车辆当前位置与障碍物的单位方向向量，方向指向车辆；以及保存车辆当前位置与目标点的单位方向向量，方向指向目标点\n",
    "\n",
    "F_rep_ob = np.zeros((len(Pobs),2))  # 存储每一个障碍到车辆的斥力,带方向\n",
    "v=np.linalg.norm(P0[2:4]) # 设车辆速度为常值"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 人工势场法实现"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "## ***************初始化结束，开始主体循环******************\n",
    "Pi = P0[0:2]  # 当前车辆位置\n",
    "# count=0\n",
    "for i in range(Num_iter):\n",
    "    if ((Pi[0] - Pg[0]) ** 2 + (Pi[1] - Pg[1]) ** 2) ** 0.5 < 1:\n",
    "        break\n",
    "    dists=[]\n",
    "    path.append(Pi)\n",
    "    # print(count)\n",
    "    # count+=1\n",
    "    #计算车辆当前位置与障碍物的单位方向向量\n",
    "    for j in range(len(Pobs)):\n",
    "        delta[j]=Pi[0:2] - Pobs[j, 0:2]\n",
    "        dists.append(np.linalg.norm(delta[j]))\n",
    "        unite_vec[j]=delta[j]/dists[j]\n",
    "    #计算车辆当前位置与目标的单位方向向量\n",
    "    delta[len(Pobs)]=Pg[0:2] - Pi[0:2]\n",
    "    dists.append(np.linalg.norm(delta[len(Pobs)]))\n",
    "    unite_vec[len(Pobs)] = delta[len(Pobs)]/dists[len(Pobs)]\n",
    "    \n",
    "    ## 计算引力\n",
    "    F_att = Eta_att*dists[len(Pobs)]*unite_vec[len(Pobs)]\n",
    "    \n",
    "    ## 计算斥力\n",
    "    # 在原斥力势场函数增加目标调节因子（即车辆至目标距离），以使车辆到达目标点后斥力也为0\n",
    "    for j in  range(len(Pobs)):\n",
    "        if dists[j] >= d0:\n",
    "            F_rep_ob[j] = np.array([0, 0])\n",
    "        else:\n",
    "            # 障碍物的斥力1，方向由障碍物指向车辆\n",
    "            F_rep_ob1_abs = Eta_rep_ob * (1 / dists[j] - 1 / d0) * (dists[len(Pobs)])**n / dists[j] ** 2  # 斥力大小\n",
    "            F_rep_ob1 = F_rep_ob1_abs*unite_vec[j]  # 斥力向量\n",
    "            # 障碍物的斥力2，方向由车辆指向目标点\n",
    "            F_rep_ob2_abs = n/2 * Eta_rep_ob * (1 / dists[j] - 1 / d0) **2 *(dists[len(Pobs)])**(n-1) # 斥力大小\n",
    "            F_rep_ob2 = F_rep_ob2_abs * unite_vec[len(Pobs)]  # 斥力向量\n",
    "            # 改进后的障碍物合斥力计算\n",
    "            F_rep_ob[j] = F_rep_ob1 + F_rep_ob2\n",
    "    \n",
    "    \n",
    "    # 增加道路边界斥力势场，根据车辆当前位置，选择对应的斥力函数\n",
    "    if Pi[1] > - d + W / 2 and Pi[1] <= - d / 2:\n",
    "         F_rep_edge = [0, Eta_rep_edge * v * np.exp(-d / 2 - Pi[1])]  # 下道路边界区域斥力势场，方向指向y轴正向\n",
    "    elif Pi[1] > - d / 2 and Pi[1] <= - W / 2:\n",
    "        F_rep_edge = np.array([0, 1 / 3 * Eta_rep_edge * Pi[1] ** 2])\n",
    "    elif Pi[1] > W / 2 and Pi[1] <= d / 2:\n",
    "        F_rep_edge = np.array([0, - 1 / 3 * Eta_rep_edge * Pi[1] ** 2])\n",
    "    elif Pi[1] > d / 2 and Pi[1] <= d - W / 2:\n",
    "        F_rep_edge = np.array([0, Eta_rep_edge * v * (np.exp(Pi[1] - d / 2))])\n",
    "    \n",
    "    \n",
    "    ## 计算合力和方向\n",
    "    F_rep = np.sum(F_rep_ob, axis=0)+F_rep_edge\n",
    "    \n",
    "    F_sum = F_att+F_rep\n",
    "    \n",
    "    UnitVec_Fsum = 1 / np.linalg.norm(F_sum) * F_sum\n",
    "    #计算车的下一步位置\n",
    "    Pi = copy.deepcopy(Pi+ len_step * UnitVec_Fsum)\n",
    "    # Pi[0:2] = Pi[0:2] + len_step * UnitVec_Fsum\n",
    "    # print(Pi)\n",
    "\n",
    "path.append(Pg[0:2]) # 最后把目标点也添加进路径中\n",
    "path=np.array(path) # 转为numpy\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 画图"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "## 画图\n",
    "fig=plt.figure(1)\n",
    "# plt.ylim(-4, 4)\n",
    "plt.axis([-10,100,-15,15])\n",
    "camera = Camera(fig)\n",
    "len_line = 100\n",
    "# 画灰色路面图\n",
    "GreyZone = np.array([[- 5, - d - 0.5], [- 5, d + 0.5],\n",
    "            [len_line, d + 0.5], [len_line, - d - 0.5]])\n",
    "for i in range(len(path)):\n",
    "     \n",
    "     plt.fill(GreyZone[:, 0], GreyZone[:, 1], 'gray')\n",
    "     plt.fill(np.array([P0[0], P0[0], P0[0] - L, P0[0] - L]), np.array([- d /\n",
    "          2 - W / 2, - d / 2 + W / 2, - d / 2 + W / 2, - d / 2 - W / 2]), 'b')\n",
    "     # 画分界线\n",
    "     plt.plot(np.array([- 5, len_line]), np.array([0, 0]), 'w--')\n",
    "\n",
    "     plt.plot(np.array([- 5, len_line]), np.array([d, d]), 'w')\n",
    "\n",
    "     plt.plot(np.array([- 5, len_line]), np.array([- d, - d]), 'w')\n",
    "\n",
    "     # 设置坐标轴显示范围\n",
    "     # plt.axis('equal')\n",
    "     # plt.gca().set_aspect('equal')\n",
    "     # 绘制路径\n",
    "     plt.plot(Pobs[:,0],Pobs[:,1], 'ro') #障碍物位置\n",
    "\n",
    "     plt.plot(Pg[0],Pg[1], 'gv')  # 目标位置\n",
    "\n",
    "     plt.plot(P0[0],P0[1], 'bs')  # 起点位置\n",
    "     # plt.cla()\n",
    "     plt.plot(path[0:i,0],path[0:i,1], 'k')  # 路径点\n",
    "     plt.pause(0.001)\n",
    "#      camera.snap()\n",
    "# animation = camera.animate()\n",
    "# animation.save('trajectory.gif')\n"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "0c7484b3574347463e16b31029466871583b0d4e5c4ad861e8848f2d3746b4de"
  },
  "kernelspec": {
   "display_name": "Python 3.8.12 ('gobigger')",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.16"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
